<template>
  <div class="mod-prod-info page-padding">
    <step1 />
    <el-form ref="dataFormRef" :model="store.v">
      <el-form-item label="状态">
        <el-radio-group v-model="store.v.status">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item
        label="产品分类"
        :rules="[{ required: true, message: '请选择产品分类' }]"
        prop="categoryId"
      >
        <el-col :span="8">
          <el-cascader
            v-model="category.selected"
            expand-trigger="hover"
            :options="category.list"
            :props="category.props"
            change-on-select
            @change="handleCategoryChange"
          />
        </el-col>
      </el-form-item> -->
      <!-- <el-form-item label="产品分组" :rules="[{ required: true, message: '请选择产品分组' }]">
        <el-col :span="8">
          <el-select v-model="store.v.tagList" multiple style="width: 250px" placeholder="请选择">
            <el-option v-for="item in tags" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-col>
      </el-form-item> -->
      <el-form-item
        label="商品标题"
        prop="goodsTitle"
        :rules="[
          { required: true, message: '商品标题不能为空' },
          { pattern: /\s\S+|S+\s|\S/, message: '请输入正确的商品标题', trigger: 'blur' },
        ]"
      >
        <template #default>
          <el-col :span="8">
            <el-input v-model="store.v.goodsTitle" placeholder="商品标题" maxlength="50" />
            <div class="text-xs text-gray-400 mt-1 leading-tight">
              商品名称建议：商品描述+属性，长度不超过60个字符
            </div>
          </el-col>
        </template>
      </el-form-item>
      <el-form-item
        label="商品描述"
        prop="brief"
        :rules="[
          {
            required: false,
            pattern: /\s\S+|S+\s|\S/,
            message: '请输入正确的商品描述',
            trigger: 'blur',
          },
        ]"
      >
        <template #default>
          <el-col :span="8">
            <el-input
              v-model="store.v.brief"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="商品描述"
            />
            <div class="text-xs text-gray-400 mt-1 leading-tight">
              商品卖点展示在商品详情标题下面，长度不超过100个字符
            </div>
          </el-col>
        </template>
      </el-form-item>
      <!-- 商品图片 -->

      <sku-tag ref="skuTagRef" :sku-list="store.v.skuList" @change="skuTagChangeSkuHandler" />
      <sku-table
        class="pr-10"
        ref="skuTableRef"
        v-model="store.v.skuList"
        :prod-name="store.v.goodsTitle"
      />
      <el-form-item label="产品详情" prop="content">
        <tiny-mce ref="contentRef" v-model="store.v.content" style="width: 1000px" />
      </el-form-item>
      <div class="shop-step-title el-bg">运费设置</div>
      store.v.deliveryMode:{{ store.v.deliveryMode }}
      store.v:{{ store.v }}
      <el-form-item label="配送方式">
        <el-checkbox-group v-model="store.v.deliveryMode">
          <el-checkbox value="hasShopDelivery">快递配送</el-checkbox>
          <el-checkbox value="hasCityDelivery">同城配送</el-checkbox>
          <el-checkbox value="hasUserPickUp">用户自提</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="运费设置">
        <el-radio-group v-model="store.v.freightType">
          <el-radio value="free">包邮</el-radio>
          <el-radio value="fixed">固定运费</el-radio>
          <el-radio value="template">运费模板</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="运费模板">
        <!-- 固定运费输入框 -->
        <div v-show="store.v.freightType === 'fixed'">
          <XInputCents
            v-model="store.v.fixedFreight"
            type="number"
            placeholder="请输入运费金额"
            style="width: 200px"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </XInputCents>
        </div>
        <!-- 运费模板选择 -->
        <div v-show="store.v.freightType === 'template'">
          <el-select
            v-model="store.v.freightTemplateId"
            placeholder="请选择运费模板"
            style="width: 200px"
          >
            <el-option
              v-for="item in transportList"
              :key="item.transportId"
              :label="item.transName"
              :value="item.transportId"
            />
          </el-select>
          <el-button
            class="ml-2"
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="onAddOrUpdateTransport()"
          >
            新增运费模板
          </el-button>
        </div>
      </el-form-item>

      <prod-transport
        v-show="store.v.deliveryMode?.hasShopDelivery"
        v-model="store.v.deliveryTemplateId"
      />

      <!-- TODO:参数设置 -->
      <!-- <div class="shop-step-title">参数设置</div> -->
      <!-- TODO:整体预览效果 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增/修改运费模板弹窗 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="getTransportList"
    />
  </div>
</template>

<script setup>
  import { ElMessage } from 'element-plus'
  import { treeDataTranslate, idList } from '@/utils/index.js'
  import ProdTransport from './components/prod-transport.vue'
  import SkuTag from './components/sku-tag.vue'
  import SkuTable from './components/sku-table.vue'
  import step1 from './components/发布商品step1.vue'
  import { Debounce } from '@/utils/debounce'
  import { ref, reactive, onMounted, nextTick } from 'vue'
  import { getProdTagList, getCategoryList, getProdInfo } from '@/plugin/Shop/api/product'
  import AddOrUpdate from '@/plugin/Shop/components/transport/add-or-update.vue'
  const emit = defineEmits(['refreshDataList'])
  const store = localStoragePinia()

  // 在store初始化时添加默认值
  store.v = {
    ...store.v, // 保留已有数据
    freightType: 'fixed', // 默认运费类型设置为固定运费
    fixedFreight: 1 // 1元（单位为分，根据XInputCents组件逻辑）
  }

  // 分类树展示与回显
  const category = reactive({
    list: [],
    selected: [],
    props: {
      value: 'categoryId',
      label: 'categoryName',
    },
  })
  // 规格列表
  // store.v = {
  //   goodsTitle: '',
  //   brief: '',
  //   pic: '',
  //   imgs: '',
  //   categoryId: 0,
  //   prodId: 0,
  //   skuList: [],
  //   tagList: [],
  //   content: '',
  //   status: 1,
  //   deliveryMode: {
  //     hasShopDelivery: false,
  //     hasUserPickUp: false,
  //   },
  //   deliveryTemplateId: null,
  // }
  const tags = ref([])
  
  const transportList = ref([])
  const addOrUpdateVisible = ref(false)
  const addOrUpdateRef = ref(null)

  onMounted(() => {
    // store.v.prodId = useRoute().query.prodId
    nextTick(() => {
      testInit()
    })
    // getDataList()
  })

  async function testInit() {
    console.log(`skuTagRef.value=>${skuTagRef.value}`)
    // dataForm.value = {
    //   ...dataForm.value,
    //   ...store.v,
    // }
    // skuTableRef.value?.init()
    skuTagRef.value?.init(store.v.skuList)
    skuTagChangeSkuHandler(store.v.skuList)
  }
  const skuTableRef = ref(null)
  const skuTagRef = ref(null)
  /**
   * 获取分类数据
   */
  const getDataList = async () => {
    // 商家入住模式没有 , 自营店铺可以选择 , 商家入住模式需要手动指定  每日上新 商城热卖 更多宝贝
    // const { data: tagList } = await getProdTagList()
    // tags.value = tagList
    const { data: categoryList } = await getCategoryList()
    category.list = treeDataTranslate(categoryList, 'categoryId', 'parentId')
    if (store.v.prodId) {
      // 获取产品数据
      const { data } = await getProdInfo({
        prodId: store.v.prodId,
      })
      store.v = data
      store.v.deliveryMode = JSON.parse(data.deliveryMode)
      skuTagRef.value?.init(data.skuList)
      skuTableRef.value?.init()
      category.selected = idList(
        category.list,
        store.v.categoryId,
        'categoryId',
        'children',
      ).reverse()
      store.v.tagList = data.tagList
    } else {
      nextTick(() => {
        dataFormRef.value?.resetFields()
        skuTagRef.value?.init()
        store.v.pic = ''
        store.v.imgs = ''
      })
    }
  }
  /**
   * 选择分类改变事件
   * @param val
   */
  const handleCategoryChange = (val) => {
    store.v.categoryId = val[val.length - 1]
  }

  const router = useRouter()
  const dataFormRef = ref(null)
  /**
   * 表单提交
   */
  const onSubmit = Debounce(() => {
    dataFormRef.value?.validate((valid) => {
      if (!valid) {
        return
      }
      if (!store.v.imgs) {
        errorMsg('请选择图片上传')
        return
      }
      if (!store.v.deliveryMode) {
        errorMsg('请选择配送方式')
        return
      }
      if (store.v.deliveryMode.hasShopDelivery && !store.v.deliveryTemplateId) {
        errorMsg('请选择运费模板')
        return
      }
      const param = Object.assign({}, store.v)
      // 设置价格和库存
      paramSetPriceAndStocks(param)

      param.deliveryMode = undefined
      param.deliveryModeVo = store.v.deliveryMode
      // 商品主图
      param.pic = store.v.imgs.split(',')[0]
      http({
        url: http.adornUrl('/prod/prod'),
        method: param.prodId ? 'put' : 'post',
        data: http.adornData(param),
      }).then(() => {
        ElMessage({
          message: '操作成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            router.push({
              path: '/prod/prodList',
            })
            emit('refreshDataList')
          },
        })
      })
    })
  })

  const paramSetPriceAndStocks = (param) => {
    // 商品库存
    param.totalStocks = 0
    // 商品价格
    param.price = 0
    // 商品原价
    param.oriPrice = 0
    // 商品实际库存
    for (let i = 0; i < param.skuList.length; i++) {
      const element = param.skuList[i]
      if (element.status !== 1) {
        continue
      }
      if (param.price === 0) {
        param.price = element.price ? Number.parseFloat(element.price) : 0
      }
      // 商品价格为最低价的那件商品的价格
      param.price = Math.min(param.price, element.price)
      if (param.price === element.price) {
        param.oriPrice = element.oriPrice ? Number.parseFloat(element.oriPrice) : 0
      }
      param.totalStocks += element.stocks ? Number.parseInt(element.stocks) : 0
    }
    // 如果sku没有商品标题，则使用商品的商品标题
    if (param.skuList.length === 1) {
      param.skuList[0].goodsTitle = store.v.goodsTitle
    }
  }
  const skuTagChangeSkuHandler = (skuList) => {
    const goodsTitle = store.v.goodsTitle
    skuList.forEach((sku) => {
      if (sku.properties) {
        sku.skuName = ''
        const properties = sku.properties.split(';')
        for (const propertiesKey in properties) {
          sku.skuName += properties[propertiesKey].split(':')[1] + ' '
        }
        sku.goodsTitle = goodsTitle + ' ' + sku.skuName
      }
    })
    store.v.skuList = skuList
  }
  const errorMsg = (message) => {
    ElMessage({
      message,
      type: 'error',
      duration: 1500,
    })
  }

  const getTransportList = async () => {
    try {
      // const { data } = await http({
      //   url: http.adornUrl('/shop/transport/page'),
      //   method: 'get',
      //   params: http.adornParams({
      //     current: 1,
      //     size: 50 // 根据需要一次性拉取一定数量的模板可用
      //   })
      // })
      transportList.value = data.records || []
    } catch (error) {
      console.error('获取运费模板列表失败:', error)
    }
  }
  getTransportList()

  const onAddOrUpdateTransport = (id) => {
    addOrUpdateVisible.value = true
    nextTick(() => {
      addOrUpdateRef.value?.init(id)
    })
  }
</script>
